#include "OgreTest2.h"
#include <OGRE/Ogre.h>
#include "stdio.h"

using Ogre::SceneType;

OgreTest2::OgreTest2(void) :
	mRoot(0),
	mWindow(0),
	mSceneMgr(0),
	mCamera(0),
	rot(0) {

}

OgreTest2::~OgreTest2(void) {
	Ogre::WindowEventUtilities::removeWindowEventListener(mWindow, this);
	delete mRoot;
	delete mWindow;
	delete mSceneMgr;
	delete mCamera;
}

bool OgreTest2::start(void) {
	configure();

	return true;
}

void OgreTest2::configure(void) {
	mRoot = new Ogre::Root("config/plugins.cfg");
	mRoot->addFrameListener(this);

	if(mRoot->restoreConfig() || mRoot->showConfigDialog()) {
		mWindow = mRoot->initialise(true, "Test");
	} else {
		//return false;
	}

	Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);

	setupScene();

	mRoot->startRendering();
}

void OgreTest2::setupScene(void) {
	mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC);

	mCamera = mSceneMgr->createCamera("PlayerCam");

	/*mCamera->setPosition(Ogre::Vector3(0, 20, 80));
	mCamera->lookAt(Ogre::Vector3(0, 0, 0));
	mCamera->setNearClipDistance(5);*/

	Ogre::Viewport* vp = mWindow->addViewport(mCamera);
	vp->setBackgroundColour(Ogre::ColourValue(0, 0, 0));

	mCamera->setAspectRatio(Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));

	mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));

	Ogre::Light* l = mSceneMgr->createLight("MainLight");
	l->setPosition(20, 80, 50);

	Ogre::Entity* entity1 = mSceneMgr->createEntity(Ogre::SceneManager::PT_CUBE);

	Ogre::SceneNode* entity1Node = mSceneMgr->getRootSceneNode()->createChildSceneNode("entity1");
	entity1Node->attachObject(entity1);
	entity1Node->setScale(0.1, 0.1, 0.1);
}

Ogre::Real OgreTest2::rotate() {
	if (rot < 360) {
		rot += 1;
	} else {
		rot = 0;
	}

    return rot;
}

bool OgreTest2::frameRenderingQueued(const Ogre::FrameEvent& evt) {
	if (mWindow->isClosed())
		return false;

	Ogre::SceneNode* node = mSceneMgr->getSceneNode("entity1");
	Ogre::Quaternion orientation(Ogre::Degree(rotate()), Ogre::Vector3::UNIT_Y);
	node->setOrientation(orientation);

	return true;
}

void OgreTest2::windowClosed(Ogre::RenderWindow* rw) {
	delete this;
}
